<template>
  <div class="header">
    <div class="header-container">
      <div class="container">
        <div class="logo">
          <!-- 声明式导航 -->
          <router-link :to="{ name: 'Home' }">
            <img src="../assets/logo.png" alt="" />
          </router-link>
        </div>
        <ul class="nav">
          <li><router-link :to="{ name: 'Home' }">首页</router-link></li>
          <li
            class="channel"
            v-for="item in channels.slice(0, 5)"
            :key="item.channelId"
          >
            <!-- <router-link :to="`/channels/${item.channelId}`">
              {{ item.name }}
            </router-link> -->
            <router-link
              :to="{
                name: 'ChannelNews',
                params: { chanId: item.channelId },
              }"
            >
              {{ item.name }}
            </router-link>
          </li>
          <li><router-link :to="{ name: 'About' }">关于</router-link></li>
        </ul>
        <div class="user">
          <!-- 情况1: 正在登录中 -->
          <span v-if="isLogining">loading...</span>
          <!-- 情况2: 已登录 -->
          <template v-else-if="loginUser">
            <router-link :to="{ name: 'Personal' }">
              {{ loginUser.nickname }}
            </router-link>
            <a href="" @click.prevent="handleLogout">退出登录</a>
          </template>
          <!-- 情况3: 未登录 -->
          <template v-else>
            <router-link :to="{ name: 'Login' }">登录</router-link>
            <router-link :to="{ name: 'Register' }">注册</router-link>
          </template>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
// import { getNewsChannels } from '../services/newsService'
import { mapState } from 'vuex'

export default {
  // data () {
  //   return {
  //     channels: []
  //   }
  // },
  // async created () {
  //   this.channels = await getNewsChannels()
  // }
  computed: {
    ...mapState('channels', ['channels', 'isLoading']),
    ...mapState('loginUser', {
      loginUser: 'data',
      isLogining: 'isLoading'
    })
  },
  methods: {
    handleLogout () {
      this.$store.dispatch('loginUser/logout')
      // 跳转到登录页面
      this.$router.push({ name: 'Login' })
    }
  }
}
</script>

<style lang="scss" scoped>
.header {
  height: 60px;
  a {
    color: #fff;
  }
}
.header-container {
  width: 100%;
  height: 60px;
  background: #000;
  color: #fff;
  line-height: 60px;
  position: fixed;
  z-index: 100;
  left: 0;
  top: 0;
  display: flex;
}
.container {
  display: flex;
}
.logo {
  a {
    display: flex;
    align-items: center;
    height: 100%;
  }
  img {
    width: 42px;
    height: 42px;
  }
}
.nav {
  margin: 0 60px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-grow: 1;
  a {
    display: block;
  }
  .router-link-exact-active {
    color: #fcb85f;
  }
  .channel .router-link-active {
    color: #fcb85f;
  }
}
.user {
  font-size: 14px;
  * {
    margin-left: 10px;
  }
}
</style>
